<template>
  <!-- 头部标题 -->
  <BasicInformation :title="title" @action="handleAction" :primary-actions="mainActions"></BasicInformation>

  <div class="add">
    <div class="common-layout">
      <el-container>
        <el-main>
          <el-row>
            <el-col :span="24">
              <div class="grid-content ep-bg-purple">
                <h4>基本信息</h4>
                <el-form :inline="true" :model="qualityOrder" :rules="rules" status-icon ref="formRef">
                  <el-form-item label="单据编号" prop="code">
                    <el-input
                        v-model="qualityOrder.code"
                        style="width: 240px"
                        placeholder="请输入单据编号"
                        clearable
                        :disabled="true"
                    />
                  </el-form-item>

                  <!-- 单据日期 -->
                  <el-form-item label="单据日期" prop="orderDate">
                    <el-date-picker
                        v-model="qualityOrder.orderDate"
                        type="date"
                        placeholder="请选择日期"
                        value-format="YYYY-MM-DD"
                        :disabled-date="disabledDate"
                    />
                  </el-form-item>

                  <el-form-item label="检验类型" prop="qualityTypeId">
                    <el-select
                        v-model="qualityOrder.qualityTypeId"
                        placeholder="请选择检验类型"
                        style="width: 240px"
                        clearable
                        filterable
                    >
                      <el-option
                          v-for="qualityType in qualityTypeList"
                          :key="qualityType.id"
                          :label="qualityType.name"
                          :value="qualityType.id"
                      />
                    </el-select>
                  </el-form-item>
                  <!-- 业务员 -->
                  <el-form-item label="质检员" prop="qualityManId">
                    <el-select
                        v-model="qualityOrder.qualityManId"
                        placeholder="请选择质检员"
                        style="width: 240px"
                        clearable
                        filterable
                    >
                      <el-option
                          v-for="user in userList"
                          :key="user.id"
                          :label="`${user.name}`"
                          :value="user.id"
                      />
                    </el-select>
                  </el-form-item>



                  <!-- 部门 -->
                  <el-form-item label="部门" prop="deptId">
                    <el-select
                        v-model="qualityOrder.deptId"
                        placeholder="请选择部门"
                        style="width: 240px;"
                        clearable
                    >
                      <el-option
                          v-for="dept in deptList"
                          :key="dept.id"
                          :label="dept.name"
                          :value="dept.id"
                      />
                    </el-select>
                  </el-form-item>
                </el-form>
              </div>
            </el-col>
          </el-row>
        </el-main>
      </el-container>
    </div>
  </div>
  <div>
    <div class="toolbar">
      <el-button type="primary">商品信息</el-button>
      <el-button @click="addDetailRow">继续添加</el-button>
      <el-button type="danger" @click="deleteSelectedRows">删除选中行</el-button>
    </div>

    <!-- 商品信息表格 -->
    <el-table :data="QualityDetail" border style="width: 100%" class="goods-table" @selection-change="newHHandleSelectionChange">
      <el-table-column type="selection" width="55" />
      <!-- 商品编码（带必填标识的下拉框） -->
      <el-table-column label="商品编码" width="150">
        <template #header>
          <span class="required-label">商品编码</span>
        </template>
        <template #default="scope">
          <el-select
              v-model="scope.row.goodsCode"
              placeholder="请选择商品"
              @change="handleGoodsChange(scope.row)"
              clearable
          >
            <el-option
                v-for="item in goodsList"
                :key="item.code"
                :label="`${item.code} - ${item.name}`"
                :value="item.code"
            />
          </el-select>
        </template>
      </el-table-column>

      <!-- 商品名称 -->
      <el-table-column label="商品名称" width="180">
        <template #default="scope">{{ scope.row.goodsName || '-' }}</template>
      </el-table-column>

      <!-- 规格型号 -->
      <el-table-column label="规格型号" width="120" align="center">
        <template #default="scope">{{ scope.row.type || '' }}</template>
      </el-table-column>


      <!-- 单位（带必填标识） -->
      <el-table-column label="单位" width="80" align="center">
        <template #header>
          <span class="required-label">单位</span>
        </template>
        <template #default="scope">{{ scope.row.unit || '件' }}</template>
      </el-table-column>


      <!--      &lt;!&ndash; 数量（带必填标识的输入框） &ndash;&gt;-->
      <!--      <el-table-column label="检验数量" width="120" align="center">-->
      <!--        <template #header>-->
      <!--          <span class="required-label">检验数量</span>-->
      <!--        </template>-->
      <!--        <template #default="scope">-->
      <!--          <el-input-number-->
      <!--              v-model="scope.row.checkNum"-->
      <!--              :min="1"-->
      <!--              :max="scope.row.checkNum || 1"-->
      <!--              controls-position="right"-->
      <!--              style="width: 100px"-->
      <!--          >-->
      <!--          </el-input-number>-->
      <!--        </template>-->
      <!--      </el-table-column>-->

      <!-- 数量（带必填标识的输入框） -->
      <el-table-column label="检验数量" width="120" align="center">
        <template #default="scope">{{ scope.row.checkNum|| 0 }}</template>
      </el-table-column>
<!--      <el-table-column label="检验数量" width="120" align="center">-->
<!--        <template #header>-->
<!--          <span class="required-label">检验数量</span>-->
<!--        </template>-->
<!--        <template #default="scope">-->
<!--          <el-input-number-->
<!--              @change = "changeNum(scope.row)"-->
<!--              v-model="scope.row.checkNum"-->
<!--              :max="scope.row.checkNum"-->
<!--              :min="0"-->
<!--              controls-position="right"-->
<!--              style="width: 100px"-->
<!--          >-->
<!--          </el-input-number>-->
<!--        </template>-->
<!--      </el-table-column>-->

      <!-- 数量（带必填标识的输入框） -->
      <el-table-column label="合格数量" width="120" align="center">
        <template #header>
          <span class="required-label">合格数量</span>
        </template>
        <template #default="scope">
          <el-input-number
              @change="changeNum(scope.row)"
              v-model="scope.row.passNum"
              :max="scope.row.checkNum"
              :min="0"
              controls-position="right"
              style="width: 100px"
          >
          </el-input-number>
        </template>
      </el-table-column>

      <el-table-column label="不合格数量" width="120" align="center">
        <template #default="scope">{{ scope.row.unPassNum || 0 }}</template>
      </el-table-column>


      <el-table-column label="备注" width="120" align="center">
        <template #default="scope">{{ scope.row.notes || '' }}</template>
      </el-table-column>


    </el-table>

  </div>
  <!--  <div class="total-summary">-->
  <!--    <div class="total-label">合计</div>-->
  <!--    <div class="total-amount">{{ formatTotal }}</div>-->
  <!--  </div>-->

  <el-dialog
      v-model="dialogVisible"
      title="采购订单"
      width="80%"
      top="5vh"
  >
    <!-- 查询条件区域 -->
    <div class="dialog-header">
      <el-input
          v-model="searchForm.code"
          placeholder="请输入单据编号"
          style="width: 240px;margin-right: 15px"
      />

      <el-button type="primary" icon="Search" @click="searchBuyOrder()">查询</el-button>
      <el-button icon="Refresh" @click="resetSearch">重置</el-button>
      <el-button icon="ArrowDown">展开</el-button>
    </div>

    <!-- 选择状态提示 -->
    <div class="selected-info">
      <span>已选择{{ selectedCount }}项</span>
      <el-button link type="primary" @click="clearSelection">清空</el-button>
    </div>

    <!-- 表格区域 -->
    <el-table
        :data="buyOrderList"
        border
        height="60vh"
        @selection-change="handleSelectionChange"

    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column prop="code" label="单据编号" width="180" />
      <el-table-column prop="get_date" label="单据日期" width="120" />
      <el-table-column prop="pro_name" label="供应商" width="120" />
      <el-table-column prop="dept_name" label="业务部门" width="120" />
      <el-table-column prop="user_name" label="业务员" width="120" />
      <el-table-column prop="closed" label="已关闭" width="100" align="center">
        <template #default="scope">
          <el-tag :type="scope.row.closed ? 'danger' : 'success'" size="small">
            {{ scope.row.closed ? '是' : '否' }}
          </el-tag>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页及操作按钮 -->
    <div class="dialog-footer">
      <!-- 分页组件 -->
      <div class="pagination-wrapper">
        <el-pagination
            background
            layout="prev, pager, next"
            :total="totalItems"
            :page-size="PopupsPageSize"
            :current-page="PopupsPageNo"
            @current-change="handlePageChange"
        />
      </div>
      <div class="action-buttons">
        <el-button @click="dialogVisible = false">关闭</el-button>
        <el-button type="primary" @click="confirmSelection">确定</el-button>
      </div>
    </div>
  </el-dialog>


</template>



<script setup lang="ts">
import { ref, reactive,withKeys ,watch,computed, onMounted} from 'vue';
import BasicInformation from '@/public-view/BasicInformation.vue';
import type {ComponentSize, FormInstance, FormRules} from 'element-plus'
import {ElInput, ElAutoResizer, ElTableV2} from 'element-plus'
import type {FunctionalComponent} from 'vue'
import type {Column, InputInstance} from 'element-plus'
import { useRouter,useRoute } from 'vue-router';
import type { SalesQuotation } from '@/types/public-xs/salesDocuments';
import type { SalesOrder } from '@/types/public-xs/salesDocuments';
import type { Goods } from '@/types/public-xs/Goods';
import type { SalesQuotationDetail } from '@/types/public-xs/salesDocuments';
import type { Customer } from '@/types/public-xs/Customer';
import axios from 'axios';
import { ElMessageBox, ElMessage } from 'element-plus'
import type { SalesOrderDetail } from '@/types/public-xs/salesDocuments';
import type {PublicProvider} from "@/types/public-cg/provider.ts";
import type {User} from "@/types/rs/User.ts";
import type {Department} from "@/types/rs/Department.ts";
import request from "@/util/request.ts";

let route=useRoute()
//质检单
let code=ref('')
//销售订单
let sourceCode=ref('')
let title=ref('质检单')
let goodsList=ref<Goods[]>([])
let pageNo=ref(1)
let pageSize=ref(5)
let allPage=ref(0)
let router=useRouter()
//部门情况
let userList=ref<User[]>([])
let selectUser=async()=>{
  let response=await request.post('per/user/getAll')
  userList.value=response.data.data
  console.log(userList.value)
}
selectUser()

let deptList=ref<Department[]>([])
let selectDept=async()=>{
  let response=await request.post('per/dept/getAll')
  deptList.value=response.data.data
  console.log(deptList.value)
}
selectDept()
//商品查询条件
const queryConditions = reactive({
  combine: '',
  kid: ''
})

const changeNum = (row:any)=>{
  row.unPassNum = row.checkNum-row.passNum
}
//填写信息区域的表单验证
const rules = reactive({
  qualityTypeId: [{ required: true, message: '请选择质检类型', trigger: 'blur' ,type:'number'}],
  code: [{ required: true, message: '请填写单据编号', trigger: 'change' }],
  qualityManId: [{ required: true, message: '请选择质检员', trigger: 'blur' }],
  deptId: [{ required: true, message: '请选择部门', trigger: 'change' }]
})
const disabledDate = (time: Date) => {
  return time.getTime() > Date.now()
}

// 修改handleAction方法
const handleAction = (action:string) => {
  switch(action) {
    case 'choose':
      if (!qualityOrder.value.qualityTypeId) {
        ElMessage.warning('请先选择质检类型')
        return
      }
      dialogVisible.value = true
      selectBuyOrderList()  // 自动触发数据加载
      break
    case 'save-add':
      insertQualityOrder()
      break;
    case 'history':
      router.push('/home/quality/page')
      break;



  }
}
async function fetchData(page: number) {
  try {
    const params = new URLSearchParams();
    params.append('pageNow', page.toString());
    params.append('pageSize', 100);
    params.append('combine', queryConditions.combine);
    params.append('kid', queryConditions.kid);

    let response = await request.post('basic/good/getGoodPage', params, {
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded'
      }
    });
    goodsList.value = response.data.data.list.map((item: any) => ({
      id: item.id,
      code: item.code,
      name: item.name,
      unique: item.unique,
      tax: item.tax,
      stock: item.stock,
      kname: item.kname
    }));
    console.log(goodsList.value)
    allPage.value = response.data.data.total || 0;
  } catch (error) {
    ElMessage.error('获取商品数据失败');
    QualityDetail.value = [];
    allPage.value = 0;
    console.error('获取数据失败:', error);
  }
}
fetchData(1)




const mainActions = ref([
  {
    name: 'save',
    label: '保存',
    type: 'primary',
    icon: 'DocumentAdd'
  },
  {
    name: 'save-add',
    label: '保存修改',
    disabled: false
  },
  {
    name: 'audit',
    label: '审核',
    hidden: false
  },
  {
    name: 'choose',
    label: '选择源单',
    hidden: false
  },
  {
    name: 'history',
    label: '历史单据',
    badge: 3 // 角标数字
  }
])
let qualityOrder=ref({
  id:null,
  code:code.value,
  orderDate:new Date,
  sourceCode:sourceCode.value,
  qualityTypeId:null,
  typeId:36,
  qualityManId: 1,
  deptId:1,
  orderStatus: 0,
  notes:'测试',
  isDelete: 0,
  createId: 1,
  createDate: new Date,
  updateId: 1,
  updateDate: new Date,
})

let addDetail=async(qualityCode:string)=>{
  for (const item of QualityDetail.value) {
    let response = await request.post('kc/qualityDetail/addQualityDetail',{
      ...item,
      qualityCode:qualityCode
    })
    // let response= await axios({
    //   url:'http://localhost:8090/qualityDetail/addQualityDetail',
    //   method:'post',
    //   data :{
    //     ...item,
    //     qualityCode:qualityCode
    //   }
    // })
  }
}

//访问方法并获取单据编号
let getDocCode=async()=>{
  let response=await request.post('xs/counter/addCode',{docType:'ZJD'})
  code.value=response.data.data
  qualityOrder.value.code = code.value
}
onMounted(async () => {
  await showInStore(route.params.code)
})


let showInStore=async(code:any)=>{
  //回显入库单
  let response1=await request.post('kc/quality/getQualityList',{
    code:code
  })

  qualityOrder.value = response1.data.data.list[0]

  let response2 = await request.post('kc/qualityDetail/getQualityDetailList', {
    qualityCode:code
  },{
    headers:{
      'Content-Type':'application/x-www-form-urlencoded'
    }
  });
  // //回显详情
  // let response2 = await axios({
  //   method:'post',
  //   url:'http://localhost:8090/qualityDetail/getQualityDetailList',
  //   data:{
  //     qualityCode:code
  //   },
  //   headers:{
  //     'Content-Type':'application/x-www-form-urlencoded'
  //   }
  // })

  QualityDetail.value = response2.data.data
  console.log(response2.data.data)
}

//动态加载质检类型
let qualityTypeList=ref([])
let selectQualityType=async()=>{
  let response=await request.post('kc/quality/selectQualityType')
  qualityTypeList.value=response.data.data
  console.log(qualityTypeList.value)
}
selectQualityType()


//获取相应的采购订单

let buyOrderList=ref([])
let selectBuyOrderList=async()=>{
  let response=await request.post("cg/CGDD/getPage",
      {
        pageNum: pageNo.value,
        pageSize: pageSize.value
      }
  )
  buyOrderList.value=response.data.data.list
  console.log(buyOrderList.value)
}




// const generateUUID = () => {
//   return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => {
//     const r = (Math.random() * 16) | 0
//     const v = c === 'x' ? r : (r & 0x3) | 0x8
//     return v.toString(16)
//   })
// }

function generateUUID() {
  const min = 100000000;
  const max = 999999999;
  return Math.floor(Math.random() * (max - min + 1)) + min;
}


const QualityDetail = ref([{
  id: generateUUID(),
  qualityCode:'',
  goodId:0,
  goodsCode:'',
  goodsName:'',
  goodsType:'',
  unit:'',
  checkNum:0,
  passNum:0,
  unPassNum:0,
  rate:0,
  notes:'',
  isDelete:0,
  createId:1,
  createDate:new Date(),
  updateId:1,
  updateDate:new Date()
}])


//选中商品数据
const handleGoodsChange = (row:any) => {
  const selected = goodsList.value.find(item => item.code === row.goodsCode)
  if (selected) {
    row.goodsName = selected.name
    row.goodId = selected.id;
    row.stock = selected.stock
    row.unit = selected.unique
    row.tax = selected.tax;
    row.kname = selected.kname
    row.stock=Math.max(1, selected.stock || 1)
  } else {
    // 清空相关字段
    row.goodsName = ''
    row.unit = '件'
    row.stock = 0
    row.stock = 1
  }
}
const newSelectedRows = ref<any[]>([])

// 处理选中行变化
const newHHandleSelectionChange = (selection: any[]) => {
  newSelectedRows.value = selection
}

// 删除选中行方法（添加确认对话框）
const deleteSelectedRows = async () => {
  if (newSelectedRows.value.length === 0) {
    ElMessage.warning('请先选择要删除的行')
    return
  }

  try {
    await ElMessageBox.confirm(
        `确定要删除选中的 ${newSelectedRows.value.length} 行吗？`,
        '删除确认',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
    )
    // 通过ID过滤实现删除
    const selectedIds = new Set(newSelectedRows.value.map(row => row.id))
    QualityDetail.value = QualityDetail.value.filter(row => !selectedIds.has(row.id))

    ElMessage.success('删除成功')
  } catch (error) {
    ElMessage.info('已取消删除')
  }
}

//
// //价格校验
// const validatePrice = (row:any) => {
//   row.actualPrice = row.actualPrice.replace(/[^\d.]/g, '')
// }
//
// // 含税价计算
// const calculateTaxPrice = (row:any) => {
//   if (row.actualPrice && row.vatRate) {
//     row.taxIncludedPrice = (row.actualPrice * (1 + row.vatRate/100)).toFixed(2)
//   }
// }



//弹窗的处理
let PopupsPageNo=ref(1)
let PopupsPageSize=ref(10)
const selectedCount = ref(0)
const totalItems = ref(0)
const dialogVisible = ref(false)
const currentSelected = ref(null)//当前选中
const selectedRows = ref([]) // 多选时使用
const searchForm = reactive({
  code: '',
})

// 表格选择处理
const handleSelectionChange = (selection:any) => {
  selectedRows.value = selection
  selectedCount.value = selection.length
  if (selection.length > 0) {
    currentSelected.value = selection[0]
  } else {
    currentSelected.value = null
  }
}



const clearSelection = () => {

}

//分页方法
let handlePageChange=()=>{

}

// 分页查询方法
const searchBuyOrder = async () => {
  try {
    const params = {
      code: searchForm.code,
      pageNum: PopupsPageNo.value,
      pageSize: PopupsPageSize.value,
    }
    let response=await request.post("cg/CGDD/getPage",
        {
          code: searchForm.code,
          pageNum: PopupsPageNo.value,
          pageSize: PopupsPageSize.value,
        }
    )
    buyOrderList.value=response.data.data.list
    totalItems.value = response.data.data.total
  } catch (error) {
    console.error('查询失败:', error)
  }
}

const resetSearch = () => {
  searchForm.code = ''
  searchBuyOrder()
}


//确认回显
const confirmSelection = async() => {
  if (currentSelected.value) {
    console.log(currentSelected.value)
    sourceCode.value = currentSelected.value.code
    ElMessage.success(`已选择源单：${currentSelected.value.code}`)
    //单据日期
    qualityOrder.value.orderDate=currentSelected.value.bili_date


    let response=await request.get("cg/CGDD/getCGDD",
        {
          params:{
            code: currentSelected.value.code,
          }
        }
    )

    QualityDetail.value= response.data.data.list.map(item => ({


      id: generateUUID(),
      qualityCode: qualityOrder.value.code || '',
      goodId: item.pid || 0,
      goodsCode: item.pcode || '',
      goodsName: item.name || '',
      goodsType:item.type || '',
      unit: item.uname || '',
      checkNum: item.num || 1,
      passNum:0,
      unPassNum:0,
      rate:0,
      notes:  '',
      isDelete: 0,
      createId: 1,
      createDate:  new Date(),
      updateId: 1,
      updateDate: new Date()
    }))


    dialogVisible.value = false
  }
}



let addDetailRow = () => {
  QualityDetail.value.push({
    id: generateUUID(),
    qualityCode:'',
    goodId:0,
    goodsCode:'',
    goodsName:'',
    goodsType:'',
    unit:'',
    checkNum:0,
    passNum:0,
    unPassNum:0,
    rate:0,
    notes:'',
    isDelete:0,
    createId:1,
    createDate:new Date(),
    updateId:1,
    updateDate:new Date()
  })
}


const formRef = ref<FormInstance>();
//点击新增后新增质检单
let insertQualityOrder =async()=>{

  if (!formRef.value) return;
  await formRef.value.validate(async (valid) => {
    if (!valid) {
      ElMessage.warning('请填写完整基本信息');
      return;
    }

    await request.get('kc/quality/delQuality', {
          params: {
            code: qualityOrder.value.code,
          }
        },
    )
    if (sourceCode.value != '') {
      qualityOrder.value.sourceCode = sourceCode.value
    }


    let response = await request.post('kc/quality/addQuality', {
          ...qualityOrder.value,
        },
    )
    await addDetail(qualityOrder.value.code)
    if (response.data.code == 200) {
      ElMessage.success('修改成功')
      router.replace('/home/quality/page')
    } else {
      ElMessage.error('修改失败')
    }
  })
}



</script>


<style scoped>
.el-row {
  margin-bottom: 20px;
}

.el-row:last-child {
  margin-bottom: 0;
}

.el-col {
  border-radius: 4px;
}

.grid-content {
  border-radius: 4px;
  min-height: 36px;
}
.required-label::after {
  content: "*";
  color: #f56c6c;
  margin-left: 4px;
}

.goods-table {
  margin-top: 20px;
}

.toolbar {
  margin-bottom: 15px;
  padding: 10px;
  background: #f5f7fa;
  border-radius: 4px;
}

.el-table :deep(.el-input__inner) {
  text-align: center;
}
.total-summary {
  background: #fff8dc; /* 浅黄色背景 */
  padding: 12px 20px;
  display: flex;
  justify-content: flex-end;
  border: 1px solid #ebeef5;
  border-top: none;
}

.total-label {
  font-weight: 600;
  color: #606266;
  margin-right: 30px;
}

.total-amount {
  color: #f56c6c;
  min-width: 120px;
  text-align: right;
  font-family: Arial, sans-serif;
}
.pagination-wrapper {
  margin-top: 16px;
  display: flex;
  justify-content: flex-end;
}
.dialog-header {
  display: flex;
  align-items: center;
  margin-bottom: 15px;
  flex-wrap: wrap;
  gap: 10px;
}

.date-label {
  color: #606266;
  margin: 0 10px;
}

.date-separator {
  margin: 0 8px;
  color: #c0c4cc;
}

.selected-info {
  margin: 12px 0;
  display: flex;
  align-items: center;
  gap: 10px;
  color: #606266;
}

.dialog-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 15px;
}

.pagination-info {
  color: #606266;
}

.action-buttons {
  display: flex;
  gap: 15px;
}

:deep(.el-dialog__header) {
  border-bottom: 1px solid #ebeef5;
}


</style>
